import React, { useEffect, FC, useState, useRef } from 'react';
import { message } from 'antd';
import TableRender from '@/biz-components/table-render';
import _, { fromPairs } from 'lodash';
import { ColumnsType } from 'antd/lib/table';
import { xhrPostJson } from '@/services';
import ModalFormWrap from './modal-form';
import { getPageMeta } from '@/services/request/meta';
import { useEventsRegister, useInitData } from './use-events';
import { PageConfig } from '@/components/schema-form-render/meta';
import { useScemaRender } from './utils';
import { EditableColField } from '@/biz-components/table-render/types';
interface hocEvents {
  tableButtonsEvents?: any,
  buttonsEvents?:any
}
interface ITableModalList {
  pageCode?: string; // 模型 code
  metasConfig?: PageConfig; // 列表页 meta
  modalMetasConfig?: PageConfig // 弹窗 编辑 meta
  noModal?: boolean; // 为 true 则为单纯列表页面
  pageApi?: string; // 分页 api
  dealMetaBeforeRender?: (config: any) => any;
  dealModalMetasBeforeRender?: (metas: any) => any; // 处理弹窗 meta模型渲染
  events?: hocEvents;
  handleSave?: (data: any) => any; // 弹窗保存方法
  rowSelection?: any; // 单据选择
  rowKey?: string; // table key
  noTableOpCol?: boolean; // 操作列是否存展示
  modalCode?: string; // 弹窗 code
  noQueryKeys?: boolean; // 兼容非元模型模式
  operWidth?: number;
  editableModals?: boolean; // 是否可编辑
  editableIdKey?: string; // 可编辑行唯一标识字段
  editableColsMap?: {
    [colKey: string]: EditableColField;
  }; // 可编辑列组件渲染信息(可编辑状态下不传，默认编辑全部列字段)
  onEditableRowSave?: (data: any) => Promise<void> | void; // 可编辑行保存回调
  nested?: boolean; // 是否可嵌套子表格
  nestedTableColumns?: ColumnsType<any>; // 嵌套表格的columns
  nestedTableDataKey?: string; // 嵌套表格数据对应主表格数据的字段
  match?: any;
  history?: any;
  extraPrams?: any;
  filedConfig?: any;
  formConfigs?: any;
  value: any[];
  eventMap?:any, // 全局处理事件map
  transform?: (a:any,b:any)=>{}
  editable?: boolean,
  onChange?:any;
  // rowsRender?: any;
  [key:string]:any;
}
const TableModal=(props: ITableModalList) => {
    const {
      metasConfig,
      modalMetasConfig,
      noModal = true,
      pageApi,
      dealMetaBeforeRender,
      dealModalMetasBeforeRender,
      events,
      handleSave,
      pageCode,
      transform,
      rowSelection = null,
      rowKey="lngType",
      noTableOpCol = false,
      modalCode = '',
      noQueryKeys = false,
      match, history, extraPrams,
      filedConfig,
      formConfigs,
      operWidth,
      editableModals = false,
      editableIdKey,
      editableColsMap,
      onEditableRowSave,
      nested = false,
      nestedTableColumns = [],
      nestedTableDataKey = '',
      editable=true,
      onChange,
      eventMap,
      scrollX,
      scrollRowNum,
      value=[],
      rowsRender = {}
    } = _.merge({}, props);
    const [remoteMetasConfig, setRemoteMetasConfig] = useState<PageConfig>({
      labelAlign: 'right',
      layout: 3,
      pageDatas: []
    });
    const [remoteModalMetasConfig, setRemoteModalMetasConfig] = useState<PageConfig>({
      labelAlign: 'right',
      layout: 3,
      pageDatas: []
    });
    const {form, SchemaFormRender} = useScemaRender(filedConfig, formConfigs);
    // 弹窗控制
    const [visible, setVisible] = useState(false);
    const [title, setTitle] = useState('新增');
    const [editData, setEditData] = useState<null | any>(null);
    // 规则类型选项
    const [loading, setLoading] = useState(false);
    const [tData=[], setData] = useState<any>(value);
    // 表格多选单选
    const [selectedRowKeys, setselectedRowKeys] = useState<string[]>([]);
    const [selectedRows, setselectedRows] = useState<any[]>([]);
    const reference = useRef();
    const selectedKeys =   useRef();
    const hookMapIns = React.useRef({
      tableButtonsEvents: {
        // 列-查看详情按钮点击事件
        handleViewClick: (id: string, row: any) => {
        },
        // 列-编辑按钮点击事件
        handleEditClick: async (id: string, row: any) => {
          if (!noModal) {
            setVisible(true);
            setTitle('编辑');
            setEditData(row);
          }
        },
        // 列-删除按钮点击事件
        handleColDleClick: async (id: string, row: any) => {
        let newArr = reference.current.reduce((total:any, current:any) => {
            current[rowKey] !== row[rowKey] && total.push(current);
            return total;
        }, []);
        reference.current = newArr;
        if(onChange){
          onChange(newArr);
        }
        setEditData([]);
        setData(newArr);
        },
        // 列-启用按钮点击事件
        handleEnableClick: async (id: string, row: any) => {
        },
        // 列-禁用按钮点击事件
        handleDisableClick: async (id: string, row: any) => {
        },
      },
      buttonsEvents: {
        // 重置
        reset: () => {
          form.reset()
        },
        // 搜索按钮点击事件
        handleSearchClick: () => {
          const values = form?.values
            loadData({ ...values }, 1, 10);
        },
        // 新增是否使用弹窗
        handleCreateBtnClick: () => {
          if (!noModal) {
            setTitle('新增');
            setEditData(null);
            setVisible(true);
          }
        },
        // 列表选中
        handleReversalBtn: async () => {
        const daa = selectedKeys.current || [];
        let newArr = reference.current.reduce((total:any, current:any) => {
          !daa.includes(current[rowKey]) && total.push(current);
            return total;
        }, []);
        reference.current = newArr;
        if(onChange){
          onChange(newArr);
        }
        setEditData([]);
        setData(newArr);
        },
      }
    })
  //

    const { schema, tableColumns, buttons, tableButtons, pageConfig } = useInitData(metasConfig, remoteMetasConfig)
    // 可选配置
    const baseRowSelection = {
      selectedRowKeys,
      onChange: (sk: any, sr: any) => {
        selectedKeys.current =  sk;
        setselectedRowKeys(sk);
        setselectedRows(sr);
      },
    };
    // 获取 row配置信息
    const getRowSelectionConfig = () => {
      if (rowSelection) {
        return {
          ...baseRowSelection,
          ...rowSelection,
        };
      }
      return null;
    };
    // 初始化数据
    const loadData = async (queryData: any, pageNo: number, pageSize: number) => {
      if (!pageApi) return
      setLoading(true);
      const queryKeys = {...queryData};
      const res: any = await xhrPostJson(pageApi, {
        queryKeys: {
          ...queryKeys,
          ...(extraPrams || {}),
          pageCode,
        },
        pageNo,
        pageSize,
        // TODO:后台处理额外参数统一放外层
        ...(noQueryKeys ? { ...queryKeys, ...(extraPrams || {}) } : {}),
      });
      reference.current = res?.result?.content || res?.result;
      const data = {
        dataSource: tDataKey(res?.result?.content || res?.result),
      }
      setData(data.dataSource);
      if(onChange){
        onChange(res?.result?.content || res?.result);
      }
      setLoading(false);
    };
    // 数据转化如果不存在id默认初始化id
    const tDataKey = (data=[])=>{
        return data?.length && data?.map((item:any, index:any)=>({[rowKey]: index+1000, ...item})) || [];
    }
    // 分页搜索
    const search = (current: number, pageSize: number) => {
      const vs = form.values
      loadData({ queryKeys: { ...vs } }, current, pageSize);
    }

    // 搜索缓存逻辑
    const handleSearchData = (dt: any = {}) => {
      const vs = form?.values
      const values = {
        ...dt,
        ...vs,
      };
      loadData({ ...values, ...dt }, 1, 10);
    };
    // 事件注册
    const { getTableTopButton, operations } = useEventsRegister(hookMapIns, events, {
      history,
      pageCode,
      noModal,
      tableButtons,
      buttons,
      loading
    }, eventMap);
    // 初始化请求页面数据
    const initData = () => {
      handleSearchData();
    }
    useEffect(() => {
      if (extraPrams && Object.keys(extraPrams).length > 0) {
        handleSearchData();
      }
    }, [JSON.stringify(extraPrams)]);
    useEffect(() => {
        if(pageApi){
          handleSearchData();
        }
    }, [pageApi]);
    useEffect(() => {
      if (value) {
        let d = [];
        if(rowKey==='index'){
          d = value.map((i, index)=>({...i, index}));
        }else {
          d = value;
        }
        setData(d)
        reference.current = d;
      }
    }, [JSON.stringify(value)])
    // 获取 metasConfig
    useEffect(() => {
      if (pageCode || modalCode) {
        try {
          if (pageCode) {
            getPageMeta(pageCode || '').then((res: any) => {
              if (res.success) {
                if (dealMetaBeforeRender) {
                  dealMetaBeforeRender(res.result);
                }
                setRemoteMetasConfig(res.result);
              }
              initData();
            });
          }
          if (modalCode) {
            getPageMeta(modalCode).then((res: any) => {
              if (res.success) {
                if (dealModalMetasBeforeRender) {
                  dealModalMetasBeforeRender(res.result);
                }
                setRemoteModalMetasConfig(res.result);
              }
            });
          }
        } catch (err) {
          console.error('请求出错', err);
        }
      }
    }, [pageCode, modalCode]);
    // 获取 Modal metas
    const getModalMetas = () => {
      const opMetas = modalCode ? remoteModalMetasConfig || [] : modalMetasConfig || [];
      return opMetas;
    };
    // 获取新增选中的数据然后传入表格
    const modalChange = (data:any)=>{
       let tableData = tData || [];
       let ta:any = [];
       // 1 如果是编辑
       if(tableData.some((item:any)=>item[rowKey]===data[rowKey]) && tableData?.length>0){
        ta = tableData?.map((item:any, index:any)=>{
           if(item[rowKey] === data[rowKey]){
            const newData = (eventMap && eventMap.transform) &&  eventMap['transform'](data, 'edit') || data;
            return {
              ...item,
              ...newData
             }
           }
           return {...item};
        })
       }else {
        const newData = (eventMap && eventMap.transform) ? eventMap['transform'](data, rowKey): (data[rowKey] ? data : { [rowKey]: Math.random(), ...data });
        if(Array.isArray(newData) && newData.length){
          ta =  [...tableData, ...newData];
        }else {
          ta =  [...tableData, newData];
        }
       }
       if(onChange){
         onChange(ta);
       }
       reference.current = ta;
        setData(ta);
        setVisible(false);
       }
    return [
      editable && (<TableRender
        rowKey={rowKey}
        metas={tableColumns || []}
        rowSelection={getRowSelectionConfig()}
        match={match}
        isRequesting={loading}
        handleSearch={search}
        extraAction={getTableTopButton()}
        operation={noTableOpCol ? null : operations}
        operWidth={operWidth}
        operAuths={tableButtons?.map(() => '')}
        // data={tData || []}
        dataSource={(eventMap && eventMap.filterData) ? eventMap.filterData(tData):  tData}
        pagination
        editable={editableModals}
        editableIdKey={editableIdKey}
        scrollRowNum={scrollRowNum}
        scrollX={scrollX}
        // editableColsMap={editableColsMap}
        // onEditableRowSave={onEditableRowSave}
        // nested={nested}
        // nestedTableColumns={nestedTableColumns}
        // nestedTableDataKey={nestedTableDataKey}
        rowsRender={ eventMap && eventMap.rowsRender || rowsRender}
      />),
      !editable && (
        <TableRender
        rowKey={rowKey}
        metas={tableColumns || []}
        match={match}
        isRequesting={loading}
        operWidth={operWidth}
        // data={tData || []}
        dataSource={tData}
        pagination={false}
        editable={editable}
        nested={false}
        rowsRender={ eventMap && eventMap.rowsRender || rowsRender}
      />
      ),
      !noModal && (
        <ModalFormWrap
          title={title}
          rowKey={rowKey}
          tableData = {tData}
          editData={editData}
          loading={loading}
          visible={visible}
          eventMap={eventMap}
          modalMetasConfig={getModalMetas()}
          onCancel={() => {
            setEditData(null);
            setVisible(false);
          }}
          onOk={async (values: any, cb: any) => {
            setLoading(true);
            if (title === '编辑') {
            }
            if (handleSave) {
              const res = await handleSave(values);
              if (res.success) {
                setVisible(false);
                message.success('保存成功');
                handleSearchData();
                setEditData(null);
                if (cb) cb();
              }
            }else{
              if (cb) cb();
              modalChange(values);
            }
            setLoading(false);
          }}
        />
      ),
    ];
  };
export default TableModal
